import { useEffect, useState } from 'react'
import './index.less'
import { InfiniteScroll, Mask, Modal, ProgressBar, Toast } from 'antd-mobile'
import { getJieJiuRecord, getJieJiuData, getJieJiuOpen } from '../../../api/active'
import { GetUserInfo } from '../../../api/mine'
import appSdk from '../../../utils/app_sdk'

let otherType = 1
let buyNum = 1
export default function SaveZodiac() {
  const [activeData, setActiveData] = useState({ list: [], aixin_num: 0, aixin_count_nums: 1000 })
  const [selectItem, setSelectItem] = useState()
  const [isPlaying, setIsPlaying] = useState(false)
  const [rewardVisible, setRewardVisible] = useState(false)
  const [rewardData, setRewardData] = useState({
    reward_data: [],
    price_count_nums: 0,
    fail_nums: 0
  })
  const [hasSpecial, setHasSpecial] = useState(false)

  const [ruleVisible, setRuleVisible] = useState(false)
  const [recordVisibale, setRecordVisibale] = useState(false)

  const [otherVisibale, setOtherVisibale] = useState(false) // 提示框状态
  const [otherTxt, setOtherTxt] = useState('') // 提示框文案

  const [userInfo, setUserInfo] = useState({ mizuan: 0 })

  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)
  const [recordList, setRecordList] = useState([])
  const getRecordList = async () => {
    try {
      const res = await getJieJiuRecord({ page })
      if (res.data && res.data?.length) {
        setRecordList(page === 1 ? res.data : recordList.concat(res.data))
      }
      if (res.data && res.data?.length >= 10) {
        setPage(page + 1)
        setHasMore(true)
      } else {
        setHasMore(false)
      }
    } catch {
      setHasMore(false)
    }
  }

  useEffect(() => {
    if (recordVisibale) {
      setPage(1)
      setHasMore(true)
      setRecordList([])
    }
  }, [recordVisibale])

  const animateCSS = (element, animation, prefix = 'animate__') =>
    // We create a Promise and return it
    new Promise((resolve, reject) => {
      const animationName = `${prefix}${animation}`
      const node = document.querySelector(element)

      node.classList.add(`${prefix}animated`, animationName)

      // When the animation ends, we clean the classes and resolve the Promise
      function handleAnimationEnd(event) {
        event.stopPropagation()
        node.classList.remove(`${prefix}animated`, animationName)
        resolve('Animation ended')
      }

      node.addEventListener('animationend', handleAnimationEnd, { once: true })
    })

  const getData = () => {
    GetUserInfo().then((res) => {
      console.log('userinfo', res)
      setUserInfo(res.data)
    })
    getJieJiuData().then((res) => {
      console.log(res)
      setActiveData(res.data)
    })
  }

  useEffect(() => {
    getData()
  }, [])

  // 开盒子 准备
  const openBox = (num) => {
    if (selectItem) {
      if (!isPlaying) {
        if (Number(userInfo.mizuan) > Number(selectItem.mizuan) * num) {
          setOtherVisibale(true)
          setOtherTxt(`是否消耗${Number(selectItem.mizuan) * (num || 1)}${window.baseConfig.coin_name}解救它`)
          otherType = 3
          buyNum = num
        } else {
          setOtherVisibale(true)
          setOtherTxt(`${window.baseConfig.coin_name}不够哦，是否立即去充值`)
          otherType = 2
        }
      } else {
        Toast.show({
          content: '请等待动画结束'
        })
      }
    } else {
      // Toast.show({
      //     content: '请选择一个要解救的动物',
      // })
      setOtherVisibale(true)
      otherType = 1
      setOtherTxt('请先选择解救哪个小动物')
    }
  }

  const requestOpen = () => {
    setIsPlaying(true)
    const { id } = selectItem
    Toast.show({
      icon: 'loading',
      content: '加载中...',
      maskClickable: false
    })
    getJieJiuOpen({
      box_id: id,
      nums: buyNum
    })
      .then((res) => {
        console.log(res)
        Toast.clear()
        animateCSS(`.glass_${id}`, 'headShake').then(() => {
          animateCSS(`.glass_${id}`, 'fadeOutUp').finally(() => {
            setIsPlaying(false)
            // 没有长度就算是吧
            if (res.data.reward_data?.length) {
              setRewardVisible(true)
              setRewardData(res.data)
            } else {
              Toast.show({
                content: '解救失败, 获得爱心值' + res.data?.aixin_nums || 0
              })
            }
            getData()
          })
        })
      })
      .catch((err) => {
        setIsPlaying(false)
        Toast.clear()
        Toast.show({
          content: err.message
        })
      })
  }

  const openSpecial = () => {
    setSpecialMask(false)
    setRewardVisible(true)
  }
  // 关闭盒子触发
  // 关闭奖励
  const [specialMask, setSpecialMask] = useState(false)
  const afterRewardClose = () => {
    setRewardVisible(false)
    // 表示有大奖
    if (rewardData.special_awards_arr && rewardData.special_awards_arr?.name && !hasSpecial) {
      setRewardData({
        ...rewardData,
        reward_data: [] // 普通 情况
      })
      setTimeout(() => {
        setHasSpecial(true)
        setSpecialMask(true) // 延迟打开
      }, 800)
    }
    // hasSpecial 表示关闭的是大奖弹窗
    if (hasSpecial) {
      setTimeout(() => {
        setHasSpecial(false)
      }, 200)
    }
  }

  return (
    <div className="zodiac_wrap">
      <div className="top_content">
        <div className="circle" onClick={() => setRecordVisibale(true)}>
          <span>记录</span>
        </div>
        <div className="title"></div>
        <div className="circle" onClick={() => setRuleVisible(true)}>
          <span>规则</span>
        </div>
      </div>
      <div className="prograss_wrap">
        <div className="prograss">
          <div className="txt"></div>
          <div className="bar"></div>
          <div className="score" style={{ width: `${((+activeData.aixin_num / +activeData.aixin_count_nums) * 100).toFixed(2)}%` }}></div>
        </div>
      </div>
      <div className="zodiac_content">
        <div className="items">
          {activeData.list.map((item) => (
            <div className={`item ${selectItem?.id === item.id && !isPlaying ? 'border' : ''}`} onClick={() => setSelectItem(item)}>
              {/*  animate__animated animate__tada animate__fadeOutUp */}
              <div className={`glass glass_${item?.id || ''}`}></div>
              <img className="img" src={item?.img} alt="" />
              <div className="yun"></div>
              <div className="base"></div>
              <div className="base2"></div>
              <div className="talk ellipsis1">{item.details}</div>
            </div>
          ))}
        </div>
      </div>
      <div className="btn_group">
        <div className="btn" onClick={() => openBox(1)}>
          {selectItem?.id ? (
            <div className="money">
              <div className="icon"></div>
              {selectItem?.mizuan}
            </div>
          ) : null}
        </div>
        {/* <div className="btn" onClick={() => openBox(10)}>
                    {
                        selectItem?.id ? <div className="money"><div className="icon"></div>{Number(selectItem?.mizuan) * 10}</div> : null
                    }
                </div> */}
      </div>

      {/* 开奖 */}
      <Modal
        visible={rewardVisible}
        onClose={afterRewardClose}
        className={`gift_modal ${hasSpecial ? 'special_reward' : ''} ${rewardData.reward_data?.length >= 3 && !hasSpecial ? 'long_wrap' : ''}`}
        closeOnMaskClick={true}
        destroyOnClose={true}
        content={
          <div className="gift_data">
            {/* <div className="gift_box_img"></div> */}
            <div className="box_tit"></div>
            <div className="tips">
              解救成功 {buyNum - rewardData.fail_nums}次，解救失败{rewardData.fail_nums}次：获得爱心值 {rewardData?.aixin_nums || 0}
            </div>
            <div className="price">
              价值：{hasSpecial ? rewardData?.special_awards_arr?.price : rewardData?.price_count_nums}
              {window.baseConfig.coin_name}
            </div>
            {/* ${rewardData.reward_data?.length} */}
            <div className={`gift_list item_${hasSpecial ? 1 : rewardData.reward_data?.length}`}>
              {(hasSpecial ? [rewardData.special_awards_arr] : rewardData.reward_data)?.map((item) => (
                <div className="item" key={item.id}>
                  {+item.nums > 1 ? <div className="nums">x{item.nums}</div> : null}
                  <img src={item.img} alt="" />
                  <div className="name ellipsis1">{item.name}</div>
                  <div className="item_price">{+item.price ? `${item.price}${window.baseConfig.coin_name}` : ''}</div>
                </div>
              ))}
            </div>
          </div>
        }
      ></Modal>

      {/* 规则 */}
      <Modal
        closeOnMaskClick={true}
        onClose={() => setRuleVisible(false)}
        visible={ruleVisible}
        className="record_modal"
        destroyOnClose
        content={
          <div className="record">
            <div className="title">活动规则&概率</div>
            <div className="list cont">
              <p>
                1、 “解救小动物”活动说明：用户可选择自己喜欢的小动物进行解救，每次解救小动物均有概率会解救成功或者是解救失败，解救成功会获得奖励道具，解救失败则会获得心动值，当心动值满则会获得一个大奖。
              </p>
              <p>
                2、 "解救小动物"旨在提升聊天室娱乐的互动性，本互动功能中所获得道具均不可进行撤销、退款或退换，不可兑换成
                {window.baseConfig.coin_name}、现金、不可再次交易; 您承诺不使用本功能进行任何违反法律法规及本平台规则、规范的活动或行为。
              </p>
              <p>
                3、  利用漏洞或者是其他非法途径参与本活动，官方有权取消其活动参与资格。{window.baseConfig.package_name}
                有权清除活动中的非法数据。
              </p>
              <p>4、  活动如有任何疑问请联系{window.baseConfig.package_name}客服。</p>
              <p>
                5、  活动获得的所有虚拟道具及权益均不可进行转让、交易或变现，{window.baseConfig.package_name}
                官方有权对任何违规行为进行处理。
              </p>
              <p>在此活动中，APPLE不是赞助者，也没有以任何形式参与活动</p>
              <p className="t">奖品详情</p>
              <div className="con">
                <img src={selectItem?.rule_img} alt="" />
              </div>
            </div>
          </div>
        }
      />

      {/* 记录 */}
      <Modal
        closeOnMaskClick={true}
        onClose={() => setRecordVisibale(false)}
        visible={recordVisibale}
        className="record_modal"
        destroyOnClose
        content={
          <div>
            <RecordDetail recordList={recordList} getRecordList={getRecordList} hasMore={hasMore} />
          </div>
        }
      />

      <Modal
        onClose={() => setOtherVisibale(false)}
        className="other"
        visible={otherVisibale}
        content={
          <div className="">
            <div className="word">{otherTxt}</div>
            <div className="btns">
              <div className="btn" onClick={() => setOtherVisibale(false)}>
                取消
              </div>
              <div
                className="btn confirm"
                onClick={() => {
                  setOtherVisibale(false)
                  // if (otherType === 1) {
                  // }
                  if (otherType === 2) {
                    appSdk('jumpToRecharge')
                  }
                  if (otherType === 3) {
                    requestOpen()
                  }
                }}
              >
                确定
              </div>
            </div>
          </div>
        }
      />

      {/* 大奖mask */}
      <Mask visible={specialMask} opacity={0.85}>
        <div className="special_reward">
          <div className="txt"></div>
          <div className="img animate__tada animate__animated"></div>
          <div className="btn" onClick={openSpecial}>
            点击领取
          </div>
        </div>
      </Mask>
    </div>
  )
}

export function RecordDetail({ recordList = [], getRecordList, hasMore }) {
  const [moreNote, setMoreNote] = useState('')
  return (
    <div className="record">
      <div className="tit">解救记录</div>
      <div className="list">
        {recordList.map((item) => (
          <div className="item_data" key={item.create_time}>
            <div
              className="item"
              onClick={() => {
                if (item.create_time === moreNote) {
                  setMoreNote(null)
                } else {
                  setMoreNote(item.create_time)
                }
              }}
            >
              <div className="info">
                <div className="name">
                  {item.box_name}x{item.nums}
                </div>
                <div className="time">{new Date(parseInt(item.create_time) * 1000).toLocaleString().replace(/:\d{1,2}$/, ' ')}</div>
              </div>
              <div className="note ellipsis1">{item.note}</div>
            </div>
            {moreNote === item.create_time ? <div className="more_note">{item.note}</div> : null}
          </div>
        ))}
        <InfiniteScroll loadMore={getRecordList} threshold={150} hasMore={hasMore} />
      </div>
    </div>
  )
}
